'''
实验名称：温湿度传感器DHT11
版本：v1.0
日期：2019.4
作者：01Studio
说明：通过编程采集温湿度数据，并在OLED上显示。。
'''

#引入相关模块
from machine import Pin,Timer
import dht,time,network
import json
import ubinascii
from simple import MQTTClient

SSID="GB"
PASSWORD="461364204"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())

CONFIG = {
    "server": "192.168.1.50", # mqtt地址
    "port":1883,  # MQTT端口（默认1883）
    "mqtt_user": "Jy4MRL5P1o7YV90PhKcR",  # 设备的访问令牌
    "mqtt_password": "Jy4MRL5P1o7YV90PhKcR",  # 设备的访问令牌
    "mqtt_topic": "device/node1/data",  # MQTT主题（无需更改）
}


#创建DTH11对象
d = dht.DHT11(Pin(14)) #传感器连接到引脚14
time.sleep(1)   #首次启动停顿1秒让传感器稳定

# 连接WiFi函数
def connectWifi(ssid,passwd):
    global wlan
    wlan=network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.disconnect()
    wlan.connect(ssid,passwd)
    while(wlan.ifconfig()[0]=='0.0.0.0'):
        time.sleep(1)

# 温湿度采集函数
def dht_get():
    d.measure()         #温湿度采集
    return d.temperature(),d.humidity()

# 上传温湿度到ThingsBoard函数
def pub_humiture(humidity, temperature):
    global c
    data={'humidity':humidity, 'temperature':temperature}
    c.publish(CONFIG["mqtt_topic"], json.dumps(data))
    print(json.dumps(data))

def pushMsg(tim):
    tem, hum=dht_get()
    pub_humiture(hum, tem)   


# 主函数
connectWifi(SSID,PASSWORD)
global c
c = MQTTClient(CLIENT_ID, CONFIG["server"],CONFIG["port"], CONFIG["mqtt_user"], CONFIG["mqtt_password"])
c.connect()
print("Connected to %s, publish to %s topic" % (CONFIG["server"], CONFIG["mqtt_topic"]))
#开启RTOS定时器，编号为-1
tim = Timer(-1)
tim.init(period=30000, mode=Timer.PERIODIC,callback=pushMsg) #周期为2000ms



